package com.zmj.sy.mom.srv.aps.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zmj.sy.mom.srv.aps.bean.entity.base.BaseEntity;
import com.zmj.sy.mom.srv.aps.bean.entity.mes.WmsPlatePick;
import com.zmj.sy.mom.srv.aps.bean.entity.order.Order;
import com.zmj.sy.mom.srv.aps.bean.entity.order.OrderAccessories;
import com.zmj.sy.mom.srv.aps.bean.entity.order.OrderBom;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.DictData;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.DictType;
import com.zmj.sy.mom.srv.aps.bean.entity.third.SinoCamPushPlan;
import com.zmj.sy.mom.srv.aps.bean.vo.aps.SelectConsVo;
import com.zmj.sy.mom.srv.aps.bean.vo.base.BaseListResVo;
import com.zmj.sy.mom.srv.aps.bean.vo.lantek.PlatePreNestStockVo;
import com.zmj.sy.mom.srv.aps.bean.vo.lantek.PlatePreNormVo;
import com.zmj.sy.mom.srv.aps.bean.vo.lantek.PlatePreStockVo;
import com.zmj.sy.mom.srv.aps.bean.vo.statsleader.StatsLeaderPlateSteelConsResVo;
import com.zmj.sy.mom.srv.aps.bean.vo.statsleader.StatsLeaderPlateSteelItemResVo;
import com.zmj.sy.mom.srv.aps.bean.vo.statsleader.StatsLeaderPlateSteelResVo;
import com.zmj.sy.mom.srv.aps.bean.vo.statsleader.StatsLeaderPlateSteelResultResVo;
import com.zmj.sy.mom.srv.aps.feign.ApsWmsApiClient;
import com.zmj.sy.mom.srv.aps.mapper.*;
import com.zmj.sy.mom.srv.aps.utils.PoiUtils;
import com.zmj.sy.mom.srv.aps.utils.SyExceptionUtils;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class StatsLeaderService {

    private final OrderAccessoriesMapper orderAccessoriesMapper;
    private final OrderMapper orderMapper;
    private final ApsWmsApiClient apsWmsApiClient;
    private final OrderBomMapper orderBomMapper;
    private final SinoCamPushPlanMapper sinoCamPushPlanMapper;
    private final WmsPlatePickMapper wmsPlatePickMapper;
    private final DictTypeMapper dictTypeMapper;
    private final DictDataMapper dictDataMapper;


    @Transactional(readOnly = true)
    public StatsLeaderPlateSteelResVo plateSteel(String constructNoList) {

        StatsLeaderPlateSteelResVo resVo = new StatsLeaderPlateSteelResVo();

        String[] constructNo = constructNoList.split(",");
        List<Order> orderList1 = orderMapper.lambdaQuery().in(Order::getConstructNo, Arrays.asList(constructNo)).eq(Order::getOrderType, 1).list();
        orderList1.sort(Comparator.comparing(Order::getConstructNo));
        List<Integer> orderIds = orderList1.stream().map(BaseEntity::getId).distinct().collect(Collectors.toList());

        String str = "δ";

        // 1.1、查询所有钢板的重量
        PlatePreStockVo platePreStockVo = apsWmsApiClient.preNestPlateStock(new PlatePreNormVo());
        DictType dictType = dictTypeMapper.lambdaQuery().eq(DictType::getDictCode, "plateTextureReplace").one();

        List<DictData> list = dictDataMapper.lambdaQuery().eq(DictData::getDictType, dictType.getId()).list();
        Map<String, String> params = new HashMap<>();
        for (DictData dictData : list) {
            params.put(dictData.getDictLabel(), dictData.getDictValue());
        }

        for (PlatePreNestStockVo platePreNestStockVo : platePreStockVo.getPlateInfo()) {
            if(platePreNestStockVo.getTexture().equals("16Mn")){
                platePreNestStockVo.setTexture("Q355B");
                platePreNestStockVo.setStandard(platePreNestStockVo.getStandard().replace("16Mn", "Q355B"));
            }
        }

        Map<String, PlatePreNestStockVo> plateResult = platePreStockVo.getPlateInfo().stream().collect(Collectors.toMap(PlatePreNestStockVo::getStandard, Function.identity()));

        // 1.2、查询已套料未出库的钢板
        List<WmsPlatePick> platePickList = wmsPlatePickMapper.lambdaQuery().in(WmsPlatePick::getPlateState, 1, 2, 3).list();
        Map<String, WmsPlatePick> platePickMap = platePickList.stream().collect(Collectors.toMap(e -> e.getPlateMaterial() + str + e.getPlateThick(), e -> e, (e1, e2) -> {
            e1.setPlateWeight(e1.getPlateWeight().add(e2.getPlateWeight()));
            return e1;
        }));

        // 1.3、算出库存可用钢板
        for (Map.Entry<String, WmsPlatePick> entry : platePickMap.entrySet()) {
            PlatePreNestStockVo platePreNestStockVo = plateResult.get(entry.getKey());
            if(platePreNestStockVo == null){
                continue;
            }
            platePreNestStockVo.setWeight(platePreNestStockVo.getWeight().subtract(entry.getValue().getPlateWeight()));
        }

        List<OrderAccessories> orderAccessories = orderAccessoriesMapper.lambdaQuery()
                .eq(OrderAccessories::getType, 1)
                .eq(OrderAccessories::getOrderType, 1)
                .in(OrderAccessories::getOrderId, orderIds)
                .likeRight(OrderAccessories::getMaterCode, "0101")
                .list();

        Map<Integer, List<OrderAccessories>> collect = orderAccessories.stream().collect(Collectors.groupingBy(OrderAccessories::getBomId));
        for (Map.Entry<Integer, List<OrderAccessories>> integerListEntry : collect.entrySet()) {
            if(integerListEntry.getValue().size() > 1){
                for (int i = 1; i < integerListEntry.getValue().size(); i++) {
                    int finalI = i;
                    orderAccessories.removeIf(e->e.getId().equals(integerListEntry.getValue().get(finalI).getId()));
                }
            }
        }

        orderAccessories.removeIf(e -> Integer.parseInt(e.getSpec().replace(str, "")) <= 10);

        List<OrderBom> orderBomList = orderBomMapper.lambdaQuery().in(OrderBom::getOrderId, orderIds).list();
        Map<Integer, OrderBom> orderBomMap1 = orderBomList.stream().collect(Collectors.toMap(BaseEntity::getId, e -> e));
        orderAccessories.removeIf(e -> !(orderBomMap1.get(e.getBomId()).getWorkChain().contains("JG") || orderBomMap1.get(e.getBomId()).getWorkChain().contains("HG")));


        for (OrderAccessories orderAccessory : orderAccessories) {
            orderAccessory.setSpec(orderAccessory.getSpec().replaceFirst(str, ""));
        }

        Map<Integer, List<OrderAccessories>> dataMap = orderAccessories.stream().collect(Collectors.groupingBy(OrderAccessories::getOrderId));

        List<Order> orderList = orderMapper.lambdaQuery().in(Order::getId, orderIds).list();
        Map<Integer, Order> orderMapById = orderList.stream().collect(Collectors.toMap(BaseEntity::getId, e -> e));

        QueryWrapper<SinoCamPushPlan> query = Wrappers.query();
        query.in("spp.order_id",  orderIds);
        query.having("sum(spp.plan_finish_amount ) > 0");
        query.groupBy("ob.order_id, ob.id");
        List<OrderBom> finishList = sinoCamPushPlanMapper.findFinishCount(query);
        Map<Integer, List<OrderBom>> finishMap = finishList.stream().collect(Collectors.groupingBy(OrderBom::getOrderId));

        Map<Integer, OrderBom> orderBomMap = orderBomMapper.lambdaQuery()
                .in(OrderBom::getOrderId, orderIds)
                .list()
                .stream()
                .collect(Collectors.toMap(BaseEntity::getId, e -> e));

        List<StatsLeaderPlateSteelConsResVo> resList = new ArrayList<>();

        Map<Integer, Order> orderMap = orderList.stream().collect(Collectors.toMap(BaseEntity::getId, e -> e));
        Map<String, Integer> map = new HashMap<>();
        int index = 1;
        for (String s : constructNo) {
            map.put(s, index++);

        }

        orderIds.sort(Comparator.comparing(e -> map.get(orderMap.get(e).getConstructNo())));
        List<StatsLeaderPlateSteelItemResVo> itemList = new ArrayList<>();
        resVo.setItemList(itemList);

        for (Integer orderId : orderIds) {

            Order order = orderMapById.get(orderId);
            if (order == null) {
                throw SyExceptionUtils.e("订单不存在");
            }

            // 1.1、查询订单定额重量
            List<OrderAccessories> allOa = dataMap.get(orderId);
            if(CollUtil.isEmpty(allOa)) {
                continue;
            }

            // 1.2、查询订单的已套料零件数量（BOMID和数量）
            List<OrderBom> orderBoms = finishMap.getOrDefault(orderId, new ArrayList<>());
            Map<Integer, OrderBom> finishOrderBomMap = orderBoms.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));

            // 1.3、算出订单未套料重量。订单未套料重量 = 订单定额重量 - 已套料零件重量
            for (OrderAccessories accessories : allOa) {
                OrderBom finishOrderBom = finishOrderBomMap.get(accessories.getBomId());
                OrderBom orderBom = orderBomMap1.get(accessories.getBomId());

                StatsLeaderPlateSteelItemResVo item = new StatsLeaderPlateSteelItemResVo();
                itemList.add(item);

                item.setOrderCode(order.getConstructNo());
                item.setOrderName(order.getMaterName());
                item.setPlmId(orderBom.getPlmId());
                item.setMaterName(orderBom.getMaterName());
                item.setMaterial(accessories.getMaterial());
                item.setThickness(Integer.parseInt(accessories.getSpec()));
                item.setTotalWeight(accessories.getPartCount());

                item.setTotalCount(orderBom.getTotalCount().multiply(new BigDecimal(order.getOrderQty())));

                if(finishOrderBom == null){
                    item.setFinishCount(BigDecimal.ZERO);
                    item.setRemainingCount(item.getTotalCount().subtract(item.getFinishCount()));
                    item.setRemainingWeight(item.getTotalWeight());
                    continue;
                }

                item.setFinishCount(finishOrderBom.getTotalCount());
                item.setRemainingCount(item.getTotalCount().subtract(item.getFinishCount()));

                BigDecimal single = accessories.getPartCount().divide(item.getTotalCount(), 8, RoundingMode.HALF_UP);
//                BigDecimal subtract = new BigDecimal(order.getOrderQty() * orderBom.getTotalCount().intValue()).subtract(finishOrderBom.getTotalCount());
//                BigDecimal totalCount = accessories.getPartCount().divide(new BigDecimal(order.getOrderQty()), 8, RoundingMode.HALF_UP).multiply(finishOrderBom.getTotalCount());
                item.setRemainingWeight(single.multiply(item.getRemainingCount()));
                accessories.setPartCount(item.getRemainingWeight());


            }
            allOa.removeIf(e -> e.getPartCount().compareTo(BigDecimal.ONE) <= 0);

        }

        List<OrderAccessories> ollOa1 = dataMap.values().stream().flatMap(Collection::stream).collect(Collectors.toList());
        Map<String, Map<String, OrderAccessories>> allOaMap = ollOa1.stream().collect(Collectors.groupingBy(e -> orderMapById.get(e.getOrderId()).getConstructNo(), Collectors.toMap(e -> e.getMaterial() + str + e.getSpec(), e -> e, (e1, e2) -> {
            e1.setPartCount(e1.getPartCount().add(e2.getPartCount()));
            return e1;
        })));


        Map<String, Map<String, List<OrderAccessories>>> nameMap = ollOa1.stream().collect(Collectors.groupingBy(e -> orderMapById.get(e.getOrderId()).getConstructNo(), Collectors.groupingBy(e -> e.getMaterial() + str + e.getSpec())));

        for (String cons : constructNo) {
            // 3.1 库存可用钢板重量 - 订单套套料重量
            Map<String, OrderAccessories> stringOrderAccessoriesMap = allOaMap.get(cons);

            if (CollUtil.isEmpty(stringOrderAccessoriesMap)) {
                continue;
            }

            for (Map.Entry<String, OrderAccessories> entry : stringOrderAccessoriesMap.entrySet()) {
                PlatePreNestStockVo platePreNestStockVo = plateResult.get(entry.getKey());
                if(platePreNestStockVo == null){
                    platePreNestStockVo = new PlatePreNestStockVo();
                    platePreNestStockVo.setWeight(BigDecimal.ZERO);
                    plateResult.put(entry.getKey(), platePreNestStockVo);
                }

                Integer bomId = entry.getValue().getBomId();
                OrderBom orderBom = orderBomMap.get(bomId);

                StatsLeaderPlateSteelConsResVo r = new StatsLeaderPlateSteelConsResVo();
                String[] split = entry.getKey().split(str);
                r.setMaterial(split[0]);
                r.setThickness(Integer.parseInt(split[1]));
//                r.setOrderId(order.getId());
                r.setConstructCode(cons);
                r.setPartName(getPartName(nameMap, cons, entry.getKey(), orderBomMap1));

                r.setBeforeTotal(platePreNestStockVo.getWeight());
                r.setTotal(entry.getValue().getPartCount().multiply(new BigDecimal("1.03")));
                platePreNestStockVo.setWeight(platePreNestStockVo.getWeight().subtract(r.getTotal()));
                r.setAfterTotal(platePreNestStockVo.getWeight());
                r.setLevel(orderBom.getLevel());
                resList.add(r);
            }
        }

        resList.sort(Comparator.comparing(StatsLeaderPlateSteelConsResVo::getConstructCode).thenComparing(StatsLeaderPlateSteelConsResVo::getMaterial).thenComparing(StatsLeaderPlateSteelConsResVo::getThickness));

        for (StatsLeaderPlateSteelConsResVo statsLeaderPlateSteelConsResVo : resList) {
            statsLeaderPlateSteelConsResVo.setBeforeTotal(statsLeaderPlateSteelConsResVo.getBeforeTotal().divide(new BigDecimal(1000), 2, RoundingMode.HALF_UP));
            statsLeaderPlateSteelConsResVo.setTotal(statsLeaderPlateSteelConsResVo.getTotal().divide(new BigDecimal(1000), 2, RoundingMode.HALF_UP));
            statsLeaderPlateSteelConsResVo.setAfterTotal(statsLeaderPlateSteelConsResVo.getAfterTotal().divide(new BigDecimal(1000), 2, RoundingMode.HALF_UP));
        }

        if(CollUtil.isNotEmpty(resList)){

            resVo.getConstructList().addAll(resList);

            List<StatsLeaderPlateSteelResultResVo> tongji = tongji(resList);
            resVo.setResultList(tongji);
        }

        return resVo;
    }

    private String getPartName(Map<String, Map<String, List<OrderAccessories>>> nameMap, String cons, String key, Map<Integer, OrderBom> orderBomMap) {
        List<OrderAccessories> orderAccessories = nameMap.get(cons).get(key);

        List<String> nameList = orderAccessories.stream()
                .map(e -> orderBomMap.get(e.getBomId()).getMaterName())
                .distinct()
                .collect(Collectors.toList());

        List<String> list = Arrays.asList("主筯", "加强板", "贴板", "顶板", "平衡耳板", "框板");

        for (String tmp : list) {
            for (String name : nameList) {
                if (name.contains(tmp)) {
                    return name;
                }
            }
        }

        Optional<String> min = nameList.stream().filter(e -> e.matches("^[\u4e00-\u9fa5]$")).min(Comparator.comparingInt(String::length));
        if (min.isPresent()) {
            return min.get();
        }
        min = nameList.stream().min(Comparator.comparingInt(String::length));
        return min.orElse("缺失名称");

    }


    @Transactional(readOnly = true)
    public Workbook exportExcel(String constructNo) {

        StatsLeaderPlateSteelResVo resVoList = plateSteel(constructNo);

        Map<String, List<StatsLeaderPlateSteelConsResVo>> collect1 = resVoList.getConstructList().stream().collect(Collectors.groupingBy(StatsLeaderPlateSteelConsResVo::getConstructCode));

        int currentRowIndex = 0;

        Workbook workbook = new XSSFWorkbook();

        Map<Integer, Short> backColor = new HashMap<>();
        backColor.put(0, IndexedColors.LIGHT_GREEN.getIndex());
        backColor.put(1, IndexedColors.LIGHT_GREEN.getIndex());
        backColor.put(2, IndexedColors.LIGHT_GREEN.getIndex());
        backColor.put(3, IndexedColors.LIGHT_GREEN.getIndex());
        backColor.put(4, IndexedColors.LIGHT_GREEN.getIndex());
        backColor.put(5, IndexedColors.LIGHT_GREEN.getIndex());
        backColor.put(6, IndexedColors.LIGHT_GREEN.getIndex());
        backColor.put(7, IndexedColors.YELLOW.getIndex());
        backColor.put(8, IndexedColors.LIGHT_TURQUOISE.getIndex());
        backColor.put(9, IndexedColors.LIGHT_TURQUOISE.getIndex());
        backColor.put(10, IndexedColors.YELLOW.getIndex());

        Map<Integer, Short> wordColor = new HashMap<>();
        wordColor.put(5, IndexedColors.RED.getIndex());
        wordColor.put(6, IndexedColors.RED.getIndex());
        wordColor.put(7, IndexedColors.RED.getIndex());

        String[] split1 = constructNo.split(",");
        Sheet sheet = workbook.createSheet("产品缺口");
        for (String cons : split1) {
            List<StatsLeaderPlateSteelConsResVo> resVoList1 = collect1.get(cons);
            if (CollUtil.isEmpty(resVoList1)) {
                continue;
            }
            List<String> collect = resVoList1.stream().map(StatsLeaderPlateSteelConsResVo::getConstructCode).distinct().collect(Collectors.toList());
            String name = "";
            for (int i = 0; i < collect.size(); i++) {
                if (i==0) {
                    name = collect.get(i);
                } else {
                    String[] split = collect.get(i).split("-");
                    name = name + "/" + split[1];
                }
            }


            // 共计 19 列（0-18）
            sheet.setColumnWidth(0, 256 * 12);
            sheet.setColumnWidth(1, 256 * 6);
            sheet.setColumnWidth(2, 256 * 20);
            sheet.setColumnWidth(3, 256 * 8);
            sheet.setColumnWidth(4, 256 * 8);
            sheet.setColumnWidth(5, 256 * 16);
            sheet.setColumnWidth(6, 256 * 12);
            sheet.setColumnWidth(7, 256 * 12);
            sheet.setColumnWidth(8, 256 * 10);
            sheet.setColumnWidth(9, 256 * 12);
            sheet.setColumnWidth(10, 256 * 10);
            sheet.setColumnWidth(11, 256 * 10);
            sheet.setColumnWidth(12, 256 * 10);
            sheet.setColumnWidth(13, 256 * 10);
            sheet.setColumnWidth(14, 256 * 10);
            sheet.setColumnWidth(15, 256 * 10);
            sheet.setColumnWidth(16, 256 * 10);
            sheet.setColumnWidth(17, 256 * 10);
            sheet.setColumnWidth(18, 256 * 10);
            sheet.setColumnWidth(19, 256 * 40);
            sheet.setColumnWidth(20, 256 * 34);


//            int currentRowIndex = 0;

            int indexAdd = currentRowIndex++;
            int firstCol = 0;
            int lastCol = 18;
            CellRangeAddress region = new CellRangeAddress(indexAdd, indexAdd, firstCol, lastCol);

            sheet.addMergedRegion(region);

            String formula1 = "当日材料缺口=WMS(未套料)-材料需求(未套料)";
            String formula2 = "实时材料缺口=实际来料+当日材料缺口";

            PoiUtils.tableName(workbook, sheet, indexAdd, true, 40, 18, String.format("结构件示范工厂%s钢板需求表", name), "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", formula1, formula2);
            PoiUtils.cells(workbook, sheet, currentRowIndex++, true, backColor, null, "产品名称", "序号", "零件名称", "材质", "规格", "材料需求(未套料)", "WMS(未套料)", "当日材料缺口",  "实际来料", "实时材料缺口", "缺料比例", "计划/到料", timeChange(LocalDate.now()), timeChange(LocalDate.now().plusDays(1)), timeChange(LocalDate.now().plusDays(2)), timeChange(LocalDate.now().plusDays(3)), timeChange(LocalDate.now().plusDays(4)), timeChange(LocalDate.now().plusDays(5)), timeChange(LocalDate.now().plusDays(6)));

            int begin = currentRowIndex;
            int end = currentRowIndex + resVoList1.size() * 2 - 1;
            CellRangeAddress region0 = new CellRangeAddress(begin, end, 0, 0);
            sheet.addMergedRegion(region0);

            int id = 1;
            for (StatsLeaderPlateSteelConsResVo vo : resVoList1) {

                int indexAdd1 = currentRowIndex++;
                int indexAdd2 = currentRowIndex++;
                for (int i = 1; i < 11; i++) {
                    int firstCol1 = i;
                    int lastCol1 = i;
                    CellRangeAddress region1 = new CellRangeAddress(indexAdd1, indexAdd2, firstCol1, lastCol1);
                    sheet.addMergedRegion(region1);
                }
                Map<Integer, Short> needBack = new HashMap<>(backColor);
                needBack.put(11, IndexedColors.PALE_BLUE.getIndex());
                needBack.put(12, IndexedColors.PALE_BLUE.getIndex());
                needBack.put(13, IndexedColors.PALE_BLUE.getIndex());
                needBack.put(14, IndexedColors.PALE_BLUE.getIndex());
                needBack.put(15, IndexedColors.PALE_BLUE.getIndex());
                needBack.put(16, IndexedColors.PALE_BLUE.getIndex());
                needBack.put(17, IndexedColors.PALE_BLUE.getIndex());
                needBack.put(18, IndexedColors.PALE_BLUE.getIndex());
                PoiUtils.cells(workbook, sheet, indexAdd1, true, needBack, null, vo.getConstructCode(), id++, vo.getPartName(), vo.getMaterial(), "δ" + vo.getThickness(), vo.getTotal(), vo.getBeforeTotal(), vo.getAfterTotal(), "0", "", "100%", "需求计划", "", "", "", "", "", "", "");
//            PoiUtils.cells(workbook, sheet, indexAdd2, true, vo.getConstructCode(), String.valueOf(id++), vo.getPartName(), vo.getMaterial(), "δ" + vo.getThickness(), vo.getTotal().setScale(0, RoundingMode.HALF_UP).toString(), vo.getBeforeTotal().setScale(0, RoundingMode.HALF_UP).toString(), vo.getAfterTotal().setScale(0, RoundingMode.HALF_UP).toString(), "0", "100%", "实际到料", "", "", "", "", "", "", "");
                PoiUtils.cells(workbook, sheet, indexAdd2, true, backColor, null, vo.getConstructCode(), "", "", "", "", "", "", "", "", "", "", "实际到料", "", "", "", "", "", "", "");
            }

        }
        BigDecimal total = resVoList.getConstructList().stream().map(StatsLeaderPlateSteelConsResVo::getTotal).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        BigDecimal before = resVoList.getConstructList().stream().map(StatsLeaderPlateSteelConsResVo::getBeforeTotal).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        BigDecimal after = resVoList.getConstructList().stream().map(StatsLeaderPlateSteelConsResVo::getAfterTotal).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);

        int indexSum = currentRowIndex++;
        CellRangeAddress region1 = new CellRangeAddress(indexSum, indexSum, 0, 4);
        sheet.addMergedRegion(region1);
        Map<Integer, Short> totalColor = new HashMap<>();
        totalColor.put(7, IndexedColors.YELLOW.getIndex());
        totalColor.put(8, IndexedColors.LIGHT_TURQUOISE.getIndex());
        totalColor.put(9, IndexedColors.LIGHT_TURQUOISE.getIndex());
        totalColor.put(10, IndexedColors.YELLOW.getIndex());
        totalColor.put(11, IndexedColors.PALE_BLUE.getIndex());
        PoiUtils.cells(workbook, sheet, indexSum, true, totalColor, wordColor, "合计", "", "", "", "", total.setScale(0, RoundingMode.HALF_UP), before.setScale(0, RoundingMode.HALF_UP), after.setScale(0, RoundingMode.HALF_UP), "0", "", "100%", "", "", "", "", "", "", "", "");

        // 零件统计
        Sheet sheetTongJi = workbook.createSheet("总计");

        sheetTongJi.setColumnWidth(0, 256 * 10);
        sheetTongJi.setColumnWidth(1, 256 * 10);
        sheetTongJi.setColumnWidth(2, 256 * 10);
        sheetTongJi.setColumnWidth(3, 256 * 10);
        sheetTongJi.setColumnWidth(4, 256 * 10);

        int indexTwo = 0;
        int id = 1;

        PoiUtils.cells(workbook, sheetTongJi, indexTwo++, true, null, null, "序号", "零件名称", "材质", "厚度", "材料缺口");
        for (StatsLeaderPlateSteelResultResVo vo : resVoList.getResultList()) {
            PoiUtils.cells(workbook, sheetTongJi, indexTwo++, true, null, null, id++, vo.getPartName(), vo.getMaterial(), vo.getThickness(), vo.getTotal());
        }

        // 零件明细
        Sheet sheetTongMx = workbook.createSheet("明细");
        sheetTongMx.setColumnWidth(0, 256 * 8);
        sheetTongMx.setColumnWidth(1, 256 * 12);
        sheetTongMx.setColumnWidth(2, 256 * 15);
        sheetTongMx.setColumnWidth(3, 256 * 25);
        sheetTongMx.setColumnWidth(4, 256 * 20);
        sheetTongMx.setColumnWidth(5, 256 * 10);
        sheetTongMx.setColumnWidth(6, 256 * 10);
        sheetTongMx.setColumnWidth(7, 256 * 10);
        sheetTongMx.setColumnWidth(8, 256 * 10);
        sheetTongMx.setColumnWidth(9, 256 * 10);
        sheetTongMx.setColumnWidth(10, 256 * 10);
        sheetTongMx.setColumnWidth(11, 256 * 10);

        int indexThree = 0;
        int idMx = 1;

        PoiUtils.cells(workbook, sheetTongMx, indexThree++, true, null, null, "序号", "施工号", "部件名称", "PLMID", "物料号", "材质", "厚度", "总重量(t)", "剩余重量(t)", "总数量", "已套料数量", "剩余数量");
        for (StatsLeaderPlateSteelItemResVo vo : resVoList.getItemList()) {
            PoiUtils.cells(workbook, sheetTongMx, indexThree++, true, null, null, idMx++, vo.getOrderCode(), vo.getOrderName(), vo.getPlmId(), vo.getMaterName(), vo.getMaterial(), vo.getThickness(), vo.getTotalWeight().divide(BigDecimal.valueOf(1000), 2, RoundingMode.HALF_UP), vo.getRemainingWeight().divide(BigDecimal.valueOf(1000), 2, RoundingMode.HALF_UP), vo.getTotalCount().intValue(), vo.getFinishCount().intValue(), vo.getRemainingCount().intValue());
        }

        return workbook;
    }

    public String timeChange(LocalDate time) {
        String[] split = time.toString().split("-");
        return split[1] + "月" + split[2] + "日";
    }


    public List<StatsLeaderPlateSteelResultResVo> tongji(List<StatsLeaderPlateSteelConsResVo> item) {
        String str = "δ";

        Map<String, StatsLeaderPlateSteelConsResVo> collect = item.stream()
                .collect(Collectors.toMap(e -> e.getMaterial() + str + e.getThickness(), e -> e, (e1, e2) -> {
                    if (e1.getAfterTotal().compareTo(e2.getAfterTotal()) < 0) {
                        return e1;
                    }
                    return e2;
                }));

        List<StatsLeaderPlateSteelConsResVo> newItem = new ArrayList<>(collect.values());
        newItem.sort(Comparator.comparing(StatsLeaderPlateSteelConsResVo::getMaterial).thenComparing(StatsLeaderPlateSteelConsResVo::getThickness));
        List<StatsLeaderPlateSteelResultResVo> result = collect.values()
                .stream()
                .sorted(Comparator.comparing(StatsLeaderPlateSteelConsResVo::getMaterial).thenComparing(StatsLeaderPlateSteelConsResVo::getThickness))
                .map(e -> {
                    StatsLeaderPlateSteelResultResVo r = new StatsLeaderPlateSteelResultResVo();
                    BeanUtils.copyProperties(e, r);
                    return r;
                })
                .collect(Collectors.toList());


        return result;
    }


    public BaseListResVo<SelectConsVo> selectCon(SelectConsVo reqVo) {
        // ERP 类型
        // 大于等于 6，小于 9
        // 不能施工号下所有零件全部套料完成
        List<Order> orderList = orderMapper.lambdaQuery()
                .eq(Order::getOrderType, 1)
                .ge(Order::getOrderStatus, 6)
                .lt(Order::getOrderStatus, 9)
                .like(StringUtils.hasText(reqVo.getConstructCode()), Order::getConstructNo, reqVo.getConstructCode())
                .list();
        if (CollUtil.isEmpty(orderList)) {
            return BaseListResVo.empty();
        }
        Map<String, List<Order>> orderConMap = orderList.stream().collect(Collectors.groupingBy(Order::getConstructNo));
        List<SelectConsVo> list = new ArrayList<>();
        for (String cons : orderConMap.keySet()) {
            List<Order> orders = orderConMap.get(cons);
            List<SinoCamPushPlan> pushPlanList = sinoCamPushPlanMapper.lambdaQuery()
                    .in(SinoCamPushPlan::getOrderId, orders.stream().map(Order::getId).collect(Collectors.toList()))
                    .list();
            if (CollUtil.isNotEmpty(pushPlanList)) {
                if (pushPlanList.stream().anyMatch(p-> p.getPlanAmount().compareTo(p.getPlanFinishAmount())>0)) {
                    SelectConsVo vo = new SelectConsVo();
                    vo.setConstructCode(cons);
                    list.add(vo);
                }
            }
        }
        return BaseListResVo.of(list, SelectConsVo.class);
    }

}
